<template>
  <div>
    <el-select clearable placeholder="请选择省份" v-model="province">
      <el-option v-for="item in areas" :key="item.code" :value="item.name">
      </el-option>
    </el-select>
    <el-select :disabled="!province" placeholder="请选择城市" v-model="city">
      <el-option v-for="item in selectCity" :key="item.code" :value="item.name"></el-option>
    </el-select>
    <el-select :disabled="!province || !city" placeholder="请选择区域" v-model="area">
      <el-option v-for="item in selectArea" :key="item.code" :value="item.name"></el-option>
    </el-select>
  </div>
</template>

<script lang='ts' setup>
import {ref, watch} from 'vue'
import allArea from '../lib/pca-code.json'

export interface AreaItem {
  name: string,
  code: string,
  children?: AreaItem[]
}

export interface Data {
  code: string,
  name: string
}

console.log(allArea)

let province = ref<string>('')
console.log('province', province)
let city = ref<string>('')
let area = ref<string>('')
let areas = ref(allArea)

let selectCity = ref<AreaItem[]>([])
let selectArea = ref<AreaItem[]>([])

//分发事件给父组件
let emits = defineEmits(['change'])

//监听选择省份
watch(() => province.value, val => {
  if (val) {
    let cities = areas.value.find(item => item.name === val)!.children!
    selectCity.value = cities
    city.value = ''
    area.value = ''
  } else {
    //province清空之后无法监听值的改变，需要此操作来清空后面input的值
    city.value = ''
    area.value = ''
  }
})

// 监听选择城市
watch(() => city.value, val => {
  if (val) {
    let area = selectCity.value.find((item: { name: string }) => item.name === val)!.children!
    selectArea.value = area
  }
  area.value = ''
})

//监听选择区域
watch(() => area.value, val => {
  let provinceData: Data = {
    code: province.value && allArea.find(item => item.name === province.value)!.code,
    name: province.value
  }

  let cityData: Data = {
    code: city.value && selectCity.value.find(item => item.name === city.value)!.code,
    name: city.value
  }

  let areaData: Data = {
    code: val && selectArea.value.find(item => item.name === val)!.code,
    name: val
  }

  emits('change', {
    province: provinceData,
    city: cityData,
    area: areaData
  })
  console.log(provinceData, cityData, areaData)
})

</script>

<style lang='scss' scoped>
.el-select {
  margin-right: 10px;
}
</style>
